package com.yuma.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class LockDedegrade {

    ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
    public void test(){
        rwlock.writeLock().lock();
        System.out.println("获取到写锁。。。。");
        //写数据
        System.out.println("写数据");

        rwlock.readLock().lock();
        System.out.println("获取到读锁----------");

        //读数据
        System.out.println("读数据");
        // 写锁解锁
        rwlock.writeLock().unlock();
        System.out.println("释放写锁==============");

        rwlock.readLock().unlock();
        System.out.println("释放读锁++++++++++++++++");
    }

    // 写锁只能降级为读锁，读锁不能升级为写锁
    public void test2() {
        rwlock.readLock().lock();
        System.out.println("开始读取...");

        rwlock.writeLock().lock();
        System.out.println("开始写...");

        rwlock.writeLock().unlock();
        System.out.println("写锁解锁");

        rwlock.readLock().unlock();
        System.out.println("读锁解锁");
    }

    public static void main(String[] args) {
        new LockDedegrade().test();
    }
}
